package com.lanju.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.lanju.common.Contants;
import com.lanju.common.SnowflakeIdWorker;
import com.lanju.common.WxMessageUtil;
import com.lanju.dao.ServiceDao;
import com.lanju.dao.SharePrizeDao;
import com.lanju.dao.UserDao;
import com.lanju.entity.Money;
import com.lanju.entity.Service_Order_Detail;
import com.lanju.entity.Service_User_Rel;
import com.lanju.entity.User;
import com.lanju.service.ServiceService;


@Service
public class ServiceServiceImpl implements ServiceService{

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceServiceImpl.class);
    
    SnowflakeIdWorker idWorker = new SnowflakeIdWorker(RandomUtils.nextLong(0,31), RandomUtils.nextLong(0,31));
    
    @Autowired
    ServiceDao serviceDao;
    @Autowired
    SharePrizeDao sharePriceDao;
    @Autowired
    UserDao userDao;
    
    
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
	public Map<String, Object> queryServiceList(Map<String, Object> param, Integer pageSize, Integer offset) {
    	Map<String, Object> rsMap = new HashMap<String, Object>();
   	 	long count = serviceDao.countServiceList(param);
        List<Map> list = serviceDao.queryServiceList(param, pageSize, offset);
        rsMap.put("total", count);
        rsMap.put("rows", list);
       return rsMap;
	}

    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
	public Map<String, Object> queryServiceDetailById(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
		List<Map> serverList = serviceDao.queryServiceDetailById(param);
		List<Map> priceList = serviceDao.queryPriceByServiceId(param);
		List<Map> imgList = serviceDao.queryImgByServiceId(param);
		rsMap.put("serverList", serverList);
		rsMap.put("priceList", priceList);
		rsMap.put("imgList", imgList);
		return rsMap;
	}

    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
	public Map<String, Object> queryUserSeerviceRel(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
		List<Map> serverUserList = serviceDao.queryUserSeerviceRel(param);
		rsMap.put("list", serverUserList);
		return rsMap;
	}

    @Override
    @Transactional(value="financialmarketingTM",  rollbackFor = Exception.class)
	public Map<String, Object> insertUserServiceOrderRel(Map<String, Object> param,HttpServletRequest request,HttpServletResponse response) {
    	Map<String, Object> res = new HashMap<String, Object>();
		try {
		Integer price=0;
		param.put("id", "o-"+idWorker.nextId());
		int hours=Integer.valueOf(param.get("hours").toString());
		//继续做下去
		Money m=sharePriceDao.hasMoney(param.get("phone").toString(),1);
		if(m!=null){
			price=m.getPrice();
			if(price<hours*Contants.YOUHUI_PRICE){//余额不足
				
			}else{
				m.setPrice(price-hours*Contants.YOUHUI_PRICE);
				sharePriceDao.mergeMoney(m);//扣款
			}
		}
		Service_User_Rel sur=new Service_User_Rel();
		sur.setAddress(param.get("address").toString());
		sur.setChargesType(param.get("chargesType").toString());
		sur.setCreateTime(new Date());
		sur.setCreator(param.get("creator").toString());
		sur.setOrderId(param.get("id").toString());
		sur.setPhone(param.get("phone").toString());
		sur.setPrice(param.get("price").toString());
		sur.setRemark(param.get("remark").toString());
		sur.setServiceCount(param.get("serviceCount").toString());
		sur.setServiceId(param.get("serviceId").toString());
		sur.setStart_serviceDate(param.get("start_serviceDate").toString());
		sur.setStatus(param.get("status").toString());
		sur.setType(param.get("type").toString());
		sur.setUserId(param.get("creator").toString());
		serviceDao.insertUserServiceOrderRel(sur);
		
		
		Service_Order_Detail sod=new Service_Order_Detail();
		sod.setCreateTime(new Date());
		sod.setHours(Integer.valueOf(param.get("hours").toString()));
		sod.setOrderDetailId("od-"+idWorker.nextId());
		sod.setOrderId( param.get("id").toString());
		sod.setStart_serviceDate(param.get("start_serviceDate").toString());
		sod.setStatus("0");
		sod.setUserId(param.get("creator").toString());
		serviceDao.insertServiceOrderDetail(sod);
    	Map<String,Object> map =new HashMap<>();
    	map.put("reviceType", "保洁提醒");
		List<User> ulist=userDao.getSendMessageUser(map);
		String templateId  ="Ukw3HWIx9QsXaoEq6riXFfJMw2MPezAMn3Bucbw7t-8";
		Integer count=0;
		User u=userDao.getById(sur.getUserId());
		if(ulist != null && ulist.size()>0){
			for(int i=0;i<ulist.size();i++){
				User u_=ulist.get(i);
				if(!StringUtils.isEmpty(u_.getOpenId())){
					String data="{\"touser\":\""+u_.getOpenId()+"\",\"template_id\":\""+templateId+"\",\"topcolor\":\"#FF0000\", "
							+ "\"data\":{\"first\": { \"value\":\""+"保洁服务预约提醒信息"+"\",\"color\":\"#173177\"},"
									+ "\"keyword1\":{\"value\":\""+"保洁服务预约"+"\",\"color\":\"#173177\" },"
											+ "\"keyword2\": { \"value\":\""+((u.getRealName()==null?u.getNickName():u.getRealName())+"("+sur.getPhone())+")\",\"color\":\"#173177\"},"
													+ "\"keyword3\":{\"value\":\""+"保洁服务"+"\",\"color\":\"#173177\"}, "
													+ "\"keyword4\":{\"value\":\""+"待受理 "+"\",\"color\":\"#173177\"}, "
													+ "\"keyword5\":{\"value\":\""+sur.getAddress()+"\",\"color\":\"#173177\"}, "
															+ "\"remark\":{\"value\":\""+"预约服务时间是："+(sur.getStart_serviceDate()+"~"+sur.getEnd_serviceDate())+"请尽快联系保洁人员处理"+"\",\"color\":\"#173177\"}"
																	+ "}}";
					synchronized (data) {
						WxMessageUtil.sendcontractPayMessage(request, response, data);
						count ++;
					}
				}	
			}
		}

		System.out.println("总共发送给"+count+"个管理员");
		res.put("result", true);    
		res.put("orderId", param.get("id").toString());
		} catch (Exception e) {
	            res.put("result", false);
	            res.put("orderId", null);
	        }
		   return res;
	}

    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
	public Map<String, Object> queryPackageList(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
   	 	long count = serviceDao.countPackageList(param);
        List<Map> list = serviceDao.queryPackageList(param);
        rsMap.put("total", count);
        rsMap.put("rows", list);
       return rsMap;
	}

    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
	public Map<String, Object> queryAreaByCity(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
        List<Map> list = serviceDao.queryAreaByCity(param);
        rsMap.put("rows", list);
       return rsMap;
	}

	@Override
	 @Transactional(value="financialmarketingTM", readOnly=true)
	public Map<String, Object> queryCommunityByArea(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
        List<Map> list = serviceDao.queryCommunityByArea(param);
        rsMap.put("rows", list);
       return rsMap;
	}

	@Override
	@Transactional(value="financialmarketingTM", readOnly=true)
	public Map<String, Object> queryPackageDetail(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
		try {
			List<Map> packageList = serviceDao.queryPackageDetail(param);
			List<Map> orderList = serviceDao.queryOrderDetail(param);
			rsMap.put("packageList", packageList);
			rsMap.put("order", orderList);
			rsMap.put("result",true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rsMap.put("result",false);
		}
        return rsMap;
	}

	@Override
	@Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
	public Map<String, Object> insertAppointTime(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
		try {
			param.put("id", UUID.randomUUID().toString());
			serviceDao.insertAppointTime(param);
			rsMap.put("res", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rsMap.put("res",false);
		}
        return rsMap;
	}

	@Override
	@Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
	public Map<String, Object> insertCollect(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
		try {
			param.put("id", UUID.randomUUID().toString());
			serviceDao.insertCollect(param);
			rsMap.put("res", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rsMap.put("res",false);
		}
        return rsMap;
	}

	@Override
	@Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
	public Map<String, Object> deleteCollect(Map<String, Object> param) {
		Map<String, Object> rsMap = new HashMap<String, Object>();
		try {
			param.put("id", UUID.randomUUID().toString());
			serviceDao.deleteCollect(param);
			rsMap.put("res", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rsMap.put("res",false);
		}
        return rsMap;
	}

	@Override
	public Map<String, Object> updateStatus(Map<String, Object> param,HttpServletRequest request,HttpServletResponse response) {
		Map<String,Object> result=new HashMap<>();
		try {
			param.put("reviceType", "保洁缴费提醒");
			Service_User_Rel sur=serviceDao.getServiceUserRel(param);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMdd-HHmmss");
			if(sur!=null){
				sur.setPayStatus(Integer.valueOf(param.get("payStatus").toString()));
				serviceDao.updateStatus(sur);
				User u=userDao.getById(sur.getUserId());
				List<User> userlist=userDao.getSendMessageUser(param);
				result.put("success", true);
				//发送信息给管理员
				if(userlist !=null && userlist.size()>0){
					for(int i=0;i<userlist.size();i++){
						User user=userlist.get(i);
						WxMessageUtil.sendPayMessage(request, response, "QP2klyuDxdQ6rU8TzH4ecHU6TOH6bK3nCV5xgGeDJNU",( u.getRealName()==null)?(u.getNickName()+"("+u.getPhone()+")"):(u.getRealName()+"("+u.getPhone()+")"), sur.getAddress(), sur.getPrice()+"元", "提醒时间:"+sdf.format(new Date()), "【保洁服务】",user.getOpenId() );
					}
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
		}
		return result;
	}

	@Override
	public Map<String, Object> updateStatusNoMsg(Map<String, Object> param,HttpServletRequest request,HttpServletResponse response) {
		Map<String,Object> result=new HashMap<>();
		try {
			param.put("reviceType", "支付管理员");
			Service_User_Rel sur=serviceDao.getServiceUserRel(param);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMdd-HHmmss");
			if(sur!=null){
				if(!StringUtils.isEmpty(param.get("payStatus"))){
					sur.setPayStatus(Integer.valueOf(param.get("payStatus").toString()));
				}
				if(!StringUtils.isEmpty(param.get("status"))){
					sur.setStatus(param.get("status").toString());
				}
				serviceDao.updateStatus(sur);
				User u=userDao.getById(sur.getUserId());
				result.put("success", true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
		}
		return result;
	}
}
